//
//  AppDelegate.swift
//  ServiceHelper
//
//  Created by Stan Wu on 15/4/6.
//  Copyright (c) 2015 Stan Wu. All rights reserved.
//

import UIKit
import AVFoundation
import AudioToolbox

let ORANGECOLOR = UIColor.init(red: 1, green: 152/255.0, blue: 1/255.0, alpha: 1)


let IPHONE_8:Int32 = 80000

//信鸽 key
/// ACCESS ID
let kXinGeAppId: UInt32 = 2200175007//填写ACCESS ID,例如:1234567890

/// ACCESS KEY
let kXinGeAppKey:String! = "IPHH3R825F4D"//填写ACCESS KEY,例如:"AB345F7H89012"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, SHLoginDelegate,UITabBarControllerDelegate ,UIActionSheetDelegate{

    var window: UIWindow?
    var alert: UIAlertView?
    var player: AVPlayer?
    var navWaitingOrders : UINavigationController!
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
      

        //信鸽注册
        XGPush.startApp(kXinGeAppId, appKey: kXinGeAppKey)
        XGPush.initForReregister { () -> Void in
            if !XGPush.isUnRegisterStatus(){
                if __IPHONE_OS_VERSION_MAX_ALLOWED >= IPHONE_8{
                    if (UIDevice.currentDevice().systemVersion.compare("8",options: .NumericSearch) != NSComparisonResult.OrderedAscending){
                        self.registerPushForIOS8()
                    }else{
                        self.registerPush()
                    }
                }else{
                    //iOS8之前注册push方法
                    //注册Push服务，注册后才能收到推送3
                    self.registerPush()
                }
            }
        }
        
        XGPush.handleLaunching(launchOptions, successCallback: { () -> Void in
            print("[XGPush]handleLaunching's successBlock\n\n")
            }) { () -> Void in
                print("[XGPush]handleLaunching's errorBlock\n\n")
        }
        

        
        let access_token = NSUserDefaults.standardUserDefaults().objectForKey("access_token") as! String?
        if access_token != nil {
            self.initTabBarController()
        }else{
            let vcLogin = SHLoginViewController()
            vcLogin.delegate = self
            window?.rootViewController = vcLogin
        }
        //Bugtags
        Bugtags.startWithAppKey("929cf63e9d9beba28298f677cbc28a04", invocationEvent:BTGInvocationEventNone)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.accessTokenInvalid), name: "AccessTokenInvalid", object: nil)
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.AccessTokenInvalidLongTime), name: "AccessTokenInvalidLongTime", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.logout), name: "LogoutAccount", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.changeWaitBadge), name: "ChangeWaitBadge", object: nil)

        
        return true
    }
    
    func registerPushForIOS8()
    {
        //Types
        if #available(iOS 8.0, *) {
            
            
            //Actions
            let acceptAction = UIMutableUserNotificationAction()
            
            acceptAction.identifier = "ACCEPT_IDENTIFIER"
            acceptAction.title      = "Accept"
            
            acceptAction.activationMode = UIUserNotificationActivationMode.Foreground
            
            acceptAction.destructive = false
            acceptAction.authenticationRequired = false
            
            
            //Categories
            let inviteCategory = UIMutableUserNotificationCategory()
            inviteCategory.identifier = "INVITE_CATEGORY";
            
            inviteCategory.setActions([acceptAction], forContext: UIUserNotificationActionContext.Default)
            inviteCategory.setActions([acceptAction], forContext: UIUserNotificationActionContext.Minimal)
            
            let categories = NSSet(objects: inviteCategory)
            
            let mySettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: categories as? Set<UIUserNotificationCategory>)
            
            UIApplication.sharedApplication().registerUserNotificationSettings(mySettings)

        } else {
            // Fallback on earlier versions
        }
        
    }
    
    func registerPush(){
//
            UIApplication.sharedApplication().registerForRemoteNotificationTypes([.Sound, .Badge, .Alert])

    }
    
    func refreshOrderList(){
        NSThread.detachNewThreadSelector(#selector(AppDelegate.loadOrderList), toTarget: self, withObject: nil)
    }
    
    func loadOrderList(){
        autoreleasepool { () -> () in
            let dict = SHDataProvider.getDealerOrderList(["order_status":"1","dealer_id":SHDataProvider.getDealerID()])
            
            let ary: [NSDictionary]? = dict?.objectForKey("data") as! [NSDictionary]?
            
            SWUtils.RunOnMainThread({ () -> Void in
                if let orderList = ary{
                    if orderList.count>0{
                        let formatter = NSDateFormatter()
                        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
                        
                        var shouldAlert = false
                        
                    
                        
                        if let current = formatter.dateFromString(orderList[0].objectForKey("create_time") as! String){
                            if let last = NSUserDefaults.standardUserDefaults().objectForKey("LatestOrderTime") as? NSDate{
                                if current.timeIntervalSinceDate(last) > 0{
                                    shouldAlert = true
                                }
                            }else{
                                shouldAlert = true;
                            }
                            
                            NSUserDefaults.standardUserDefaults().setObject(current, forKey: "LatestOrderTime")
                        }

                        if shouldAlert{
                            NSNotificationCenter.defaultCenter().postNotificationName("RefreshOrderList", object: nil)
                            self.alert = UIAlertView(title: nil, message: "有新的预约单待处理", delegate: nil, cancelButtonTitle: "确定");
                            self.alert?.show()
                            
                            self.playSound()
                            
                            NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: #selector(AppDelegate.dismissAlert), userInfo: nil, repeats: false)
                        }
                    }
                }
                

                
                
            })
        }
    }
    
    func dismissAlert(){
        alert?.dismissWithClickedButtonIndex(0, animated: false);
    }
    
    func playSound(){
        if player == nil{
            let path = NSBundle.mainBundle().pathForResource("alert", ofType: "mp3")
            player = AVPlayer(URL: NSURL.fileURLWithPath(path!))
        }
        
        player?.seekToTime(CMTimeMake(0, 60))
        
        player?.play()
        
        AudioServicesPlaySystemSound(UInt32(kSystemSoundID_Vibrate))

    }
    
    func accessTokenInvalid(){
        if let vc = window?.rootViewController{
            if !(vc is SHLoginViewController){
                logout()
                UIAlertView.show(nil, message: "您的账号已在其他设备上登录", cancelButton: nil)
            }
        }
    }
    
    func AccessTokenInvalidLongTime(){
        if let vc = window?.rootViewController{
            if !(vc is SHLoginViewController){
                logout()
                UIAlertView.show(nil, message: "此次登录已失效", cancelButton: nil)
            }
        }
    }
    
    
    
    func logout(){
        NSUserDefaults.standardUserDefaults().removeObjectForKey("access_token")
        let vcLogin = SHLoginViewController()
        vcLogin.delegate = self
        window?.rootViewController = vcLogin
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func accountLoginned() {
//        let vcHome = SHHomeViewController()
//        self.window?.rootViewController = vcHome
        
//        let vcMain = SHMainViewController()
//        self.window?.rootViewController = vcMain;
        
        if let uid = SHDataProvider.getUserInfo()?.objectForKey("uid") as! String!{
            XGPush.setAccount(uid)
        }

        let strDeviceToken = NSUserDefaults.standardUserDefaults().objectForKey("deviceToken")
        NSThread.detachNewThreadSelector(#selector(AppDelegate.bindDeviceToken(_:)), toTarget: self, withObject: strDeviceToken)
        self.initTabBarController()

    }
    
    func changeWaitBadge(){
         let badgeVaue = NSUserDefaults.standardUserDefaults().integerForKey("OrdersCount")
         if badgeVaue > 0{
            navWaitingOrders.tabBarItem.badgeValue = "\(badgeVaue)"
         }else{
            navWaitingOrders.tabBarItem.badgeValue = nil
        }
          
        
       
        
    }
    
    
    func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
        let navVc = viewController as! UINavigationController
        if navVc.viewControllers[0].isKindOfClass(SHSettingViewController.classForCoder()){
            print("弹出退出登录")
//            navVc.tabBarItem.image=UIImage(named: "gary_set_up.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
//            navVc.tabBarItem.selectedImage=UIImage(named:
//                "bule_set_up.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);

                        let actionSheet = UIActionSheet()
                        actionSheet.title = "选择要进行的操作"
                        actionSheet.delegate = self
                        actionSheet.addButtonWithTitle("退出登录")
                        actionSheet.addButtonWithTitle("取消")
                        actionSheet.tag = 100
//                        actionSheet.showFromTabBar(tabBarController.tabBar)
                        actionSheet.showInView((self.window?.rootViewController?.view)!)
            return false
        }else{
            return true
        }
    }
    
    func initTabBarController(){
        let vcOrdersList = SHOrdersListViewController()
        let navOrdersList = UINavigationController(rootViewController: vcOrdersList)
        navOrdersList.title = "全部订单"
        navOrdersList.tabBarItem.image=UIImage(named: "gary_all_orders.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
        navOrdersList.tabBarItem.selectedImage=UIImage(named: "bule_all_orders.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //选中后的图片
        navOrdersList.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -3)
        //        let allItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 1)
        //        vcOrdersList.tabBarItem = allItem
        //        vcOrdersList.strNavTitle = "全部订单"
        
        
        let vcWaitingOrders = SHOrdersListViewController()
        vcWaitingOrders.isFromWaitingOrder = true
        navWaitingOrders = UINavigationController(rootViewController: vcWaitingOrders)
        navWaitingOrders.title = "等待确认"
        
        navWaitingOrders.tabBarItem.image=UIImage(named: "gary_waiting.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
        navWaitingOrders.tabBarItem.selectedImage=UIImage(named:
            "bule_waiting.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
        navWaitingOrders.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -3)
        //        navWaitingOrders.tabBarItem.tag = 1
        //选中后的图片
        //        vcWaitingOrders.isFromWaitingOrder = true
        //        vcWaitingOrders.strNavTitle = "等待确认"
        //        let waitingItem = UITabBarItem(tabBarSystemItem: .Favorites, tag: 1)
        //        vcWaitingOrders.tabBarItem = waitingItem
        let vcSetting  = SHSettingViewController()
        let navSetting = UINavigationController(rootViewController: vcSetting)
        navSetting.title = "系统设置"
        navSetting.tabBarItem.image=UIImage(named: "gary_set_up.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal); //默认显示图片
        navSetting.tabBarItem.selectedImage=UIImage(named:
            "bule_set_up.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
        navSetting.tabBarItem.tag = 2
        navSetting.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -3)
        
        let tabbar_zsj = UITabBarController()
        tabbar_zsj.delegate = self
        
        let controls = [navOrdersList,navWaitingOrders as UIViewController,navSetting]
        //        tabbar_zsj.setViewControllers(controls, animated: true)
        //.自定义工具栏
        tabbar_zsj.tabBar.backgroundColor=UIColor.clearColor()
        //底部工具栏背景颜色
        tabbar_zsj.tabBar.barTintColor=UIColor(red: 0.93, green: 0.93, blue: 0.93, alpha: 1)
        //.设置底部工具栏文字颜色（默认状态和选中状态）
        UITabBarItem.appearance().setTitleTextAttributes(NSDictionary(object:UIColor.grayColor(), forKey:NSForegroundColorAttributeName) as? [String : AnyObject], forState:UIControlState.Normal);
        UITabBarItem.appearance().setTitleTextAttributes(NSDictionary(object:ORANGECOLOR, forKey:NSForegroundColorAttributeName) as? [String : AnyObject], forState:UIControlState.Selected)
        
        //设置开始选中那个控制器
        tabbar_zsj.selectedIndex = 1
        /**********************************************************/
        // 微标签 的设置
        
        /**********************************************************/
        
        // 将三个标签，添加到标签栏控制器
        tabbar_zsj.viewControllers = controls
        /**********************************************************/
         //这个方法，必须在，所有的标签都设置到tabbar 上才可以设置，否则报错
         //        tabbar_zsj.selectedViewController = vcOrdersList
         /*
         错误是：eason: '-[UITabBarController setSelectedViewController:] only a view controller in the tab bar controller's list of view controllers can be selected.
         */
         //添加到widows 上面进行显示
        self.window?.rootViewController = tabbar_zsj
    }
    
    // MARK: - UIActionSheet Delegate
    func actionSheet(actionSheet: UIActionSheet, didDismissWithButtonIndex buttonIndex: Int) {
        if actionSheet.tag == 100 {
            if buttonIndex >= 0 {
                let buttonTitle = actionSheet.buttonTitleAtIndex(buttonIndex)
                if buttonTitle=="退出登录"{
                    NSNotificationCenter.defaultCenter().postNotificationName("LogoutAccount", object: nil)
                }
                
            }
        }
    }
    
    func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
        XGPush.localNotificationAtFrontEnd(notification, userInfoKey: "clockID", userInfoValue: "myid")
        
        XGPush.delLocalNotification(notification)
    }
    
    
    @available(iOS, introduced=8.0)
    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
        UIApplication.sharedApplication().registerForRemoteNotifications()
    }
    @available(iOS, introduced=8.0)
    func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
        
        if let ident = identifier
        {
            if ident == "ACCEPT_IDENTIFIER"
            {
                print("ACCEPT_IDENTIFIER is clicked\n\n")
            }
        }
        
        completionHandler()
    }
    
    
    
    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        //注册设备
        //        XGSetting.getInstance().Channel = ""//= "appstore"
        //        XGSetting.getInstance().GameServer = "家万户"
        
//        var str = NSMutableString.init()
//        var token = deviceToken.bytes as! AnyObject
//        var len = deviceToken.length
//        
//        for i in 0 ..< len {
////            str.appendFormat("%@=%@", key,dictParamNew.objectForKey(key) as! String!)
//           str.appendFormat("%2x", token[i])
//        }
        
       
        
        let deviceTokenStr = XGPush.registerDevice(deviceToken, successCallback: { () -> Void in
            print("[XGPush]register successBlock\n\n")
//            UIAlertView.show(nil, message: "信鸽推送集成OK", cancelButton: nil)

            }) { () -> Void in
                print("[XGPush]register errorBlock\n\n")
//                UIAlertView.show(nil, message: "信鸽推送集成失败", cancelButton: nil)
        }
        
        print("deviceTokenStr:\(deviceTokenStr)\n\n")
        
        NSUserDefaults.standardUserDefaults().setObject(deviceTokenStr, forKey: "deviceToken")
        NSThread.detachNewThreadSelector(#selector(AppDelegate.bindDeviceToken(_:)), toTarget: self, withObject: deviceTokenStr)
        if let uid = SHDataProvider.getUserInfo()?.objectForKey("uid") as! String!{
           XGPush.setAccount(uid)
            let tokenss = XGPush.registerDevice(deviceToken)
            NSUserDefaults.standardUserDefaults().setObject(tokenss, forKey: "APNSDeviceToken")
        }
        

        
    }
    
    func bindDeviceToken(strDeviceToken: String){
        autoreleasepool { () -> () in
            var dict : NSDictionary
            if let uid = SHDataProvider.getUserInfo()?.objectForKey("uid") as! String!{
                dict = SHDataProvider.bindDeviceToken(["device_token":strDeviceToken,"uid":uid])!
            }else{
                 dict = SHDataProvider.bindDeviceToken(["device_token":strDeviceToken])!
            }
            
            
            print(dict)
            SWUtils.RunOnMainThread({ () -> Void in
                if let code = dict.objectForKey("code")?.intValue{
                    if code==200{

                        print("绑定Device Token成功");
                    }else{
                        print("绑定Device Token成功");
                    }
                }else{
                     print("绑定Device Token失败");
                }

   
            })
        }
    }

    
    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        print("didFailToRegisterForRemoteNotifications error:\(error.localizedDescription)\n\n")
    }
    
    // iOS 3 以上
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        
        //        UIAlertView(title: "3-", message: "didReceive", delegate: self, cancelButtonTitle: "OK").show()
        let apsDictionary = userInfo["aps"] as? NSDictionary
        if let apsDict = apsDictionary
        {
             NSNotificationCenter.defaultCenter().postNotificationName("RefreshOrderList", object: nil)
            let alertView = UIAlertView(title: "您有新的消息", message: apsDict["alert"] as? String, delegate: self, cancelButtonTitle: "确定")
            alertView.show()
        }
        
        // 清空通知栏通知
        XGPush.clearLocalNotifications()
        UIApplication.sharedApplication().cancelAllLocalNotifications()
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
        
        XGPush.handleReceiveNotification(userInfo)
    }
    
    // iOS 7 以上
    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)
    {
        //        UIAlertView(title: "7-", message: "didReceive", delegate: self, cancelButtonTitle: "OK").show()
        let apsDictionary = userInfo["aps"] as? NSDictionary
         NSNotificationCenter.defaultCenter().postNotificationName("RefreshOrderList", object: nil)
        if let apsDict = apsDictionary
        {
            let alertView = UIAlertView(title: "您有新的消息", message: apsDict["alert"] as? String, delegate: self, cancelButtonTitle: "确定")
            alertView.show()
        }
        
        // 清空通知栏通知
        XGPush.clearLocalNotifications()
        UIApplication.sharedApplication().cancelAllLocalNotifications()
        UIApplication.sharedApplication().applicationIconBadgeNumber = 0
        
        XGPush.handleReceiveNotification(userInfo)
    }

    
    func isInTestStatus() -> Bool{
        return true
    }
    
}

